import 'dart:io';

import 'package:image_picker_plus_nic/image_picker_plus_nic.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Custom gallery display',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: SafeArea(
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              normal1(context),
              normal2(context),
              normal3(context),
              normal4(context),
              // preview1(context),
              // preview2(context),
              // preview3(context),
              // camera1(context),
              // camera2(context),
            ]),
      ),
    );
  }

  ElevatedButton normal1(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        UiTexts uiTexts = const UiTexts(
            titleGallery: "相簿", titleCrop: "裁切", ok: "確定", cancel: "取消");
        SelectedImagesDetails? details =
            await picker.pickImage(source: ImageSource.camera, uiText: uiTexts, primaryColor: Color(0xff1fc97b), textStyle: TextStyle());
        //print('details.index=${details?.selectedFiles.first.index}');
        if (details != null) await displayDetails(details);
      },
      child: const Text("開相機"),
    );
  }

  ElevatedButton normal2(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        UiTexts uiTexts = const UiTexts(
            titleGallery: "相簿", titleCrop: "裁切", ok: "確定", cancel: "取消");
        SelectedImagesDetails? details = await picker.pickImage(
            source: ImageSource.gallery, uiText: uiTexts, primaryColor: Color(0xff1fc97b), textStyle: TextStyle());
        //print('details.index=${details?.selectedFiles.first.index}');
        if (details != null) await displayDetails(details);
      },
      child: const Text("從相簿單選照片"),
    );
  }

  ElevatedButton normal3(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        UiTexts uiTexts = const UiTexts(
            titleGallery: "相簿", titleCrop: "裁切", ok: "確定", cancel: "取消");
        SelectedImagesDetails? details = await picker.pickAndCropImage(
            source: ImageSource.gallery, uiText: uiTexts, selectIndex: 15, primaryColor: Color(0xff1fc97b), textStyle: TextStyle());
        if (details != null) await displayDetails(details);
      },
      child: const Text("裁切圖片"),
    );
  }

  ElevatedButton normal4(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        ImagePickerPlus picker = ImagePickerPlus(context);
        UiTexts uiTexts = const UiTexts(
            titleGallery: "相簿",
            titleCrop: "裁切",
            ok: "確定",
            multiOk: '確認上傳 (%d/%d)',
            cancel: "取消");
        final details = await picker.pickMultiImage(
            source: ImageSource.gallery, uiText: uiTexts, primaryColor: Color(0xff1FC97B), textStyle: TextStyle());
        if (details != null) await displayDetails(details);
      },
      child: const Text("相簿多選"),
    );
  }

  Future<void> displayDetails(SelectedImagesDetails details) async {
    await Navigator.of(context).push(
      CupertinoPageRoute(
        builder: (context) {
          return DisplayImages(
              selectedBytes: details.selectedFiles,
              details: details,
              aspectRatio: details.aspectRatio);
        },
      ),
    );
  }
}

class DisplayImages extends StatefulWidget {
  final List<SelectedByte> selectedBytes;
  final double aspectRatio;
  final SelectedImagesDetails details;
  const DisplayImages({
    Key? key,
    required this.details,
    required this.selectedBytes,
    required this.aspectRatio,
  }) : super(key: key);

  @override
  State<DisplayImages> createState() => _DisplayImagesState();
}

class _DisplayImagesState extends State<DisplayImages> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Selected images/videos')),
      body: ListView.builder(
        itemBuilder: (context, index) {
          SelectedByte selectedByte = widget.selectedBytes[index];
          if (!selectedByte.isThatImage) {
            return _DisplayVideo(selectedByte: selectedByte);
          } else {
            return SizedBox(
              width: double.infinity,
              child: Image.file(selectedByte.selectedFile),
            );
          }
        },
        itemCount: widget.selectedBytes.length,
      ),
    );
  }
}

class _DisplayVideo extends StatefulWidget {
  final SelectedByte selectedByte;
  const _DisplayVideo({Key? key, required this.selectedByte}) : super(key: key);

  @override
  State<_DisplayVideo> createState() => _DisplayVideoState();
}

class _DisplayVideoState extends State<_DisplayVideo> {
  late VideoPlayerController controller;
  late Future<void> initializeVideoPlayerFuture;

  @override
  void initState() {
    super.initState();
    File file = widget.selectedByte.selectedFile;
    controller = VideoPlayerController.file(file);
    initializeVideoPlayerFuture = controller.initialize();
    controller.setLooping(true);
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: initializeVideoPlayerFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return Stack(
            alignment: Alignment.center,
            children: [
              AspectRatio(
                aspectRatio: controller.value.aspectRatio,
                child: VideoPlayer(controller),
              ),
              Align(
                alignment: Alignment.center,
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      if (controller.value.isPlaying) {
                        controller.pause();
                      } else {
                        controller.play();
                      }
                    });
                  },
                  child: Icon(
                    controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
                    color: Colors.white,
                    size: 45,
                  ),
                ),
              )
            ],
          );
        } else {
          return const Center(
            child: CircularProgressIndicator(strokeWidth: 1),
          );
        }
      },
    );
  }
}
